<?php

namespace App\Models\Purchase;

use App\Models\Balance\Balance;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class PurchaseWarehousingOrderwithpay extends Model
{
    protected $table = 'purchase_warehousing_orderwithpay';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];
    /**
     *获取列表 
     */
    public static function getList(Request $request, $cpid, $manger_id=0)
    {
        $query = self::with(['orderinfo'])->where(['cpid' => $cpid, 'is_del' => 1])->orderBy('create_at', 'desc');
        if ($manger_id > 0) {
            $query->where('manger_id', $manger_id);
        }

        $type = $request->type ?? 0;
        if (in_array($type, [1, 2])) {
            $query->where('type', $type);
        }

        $company_name=$request->company_name;

        if($company_name){
            $query->where('company_name', 'like', '%' . $company_name . '%');
        }

        $pa_settle_company_name = $request->pa_settle_company_name; //结算公司名称
        if ($pa_settle_company_name != '') {
            $query->where('pa_settle_company_name', 'like', '%' . $pa_settle_company_name . '%');
        }

        $get_balance = intval($request->get_balance); //获取供应商余额
        $custom_id=intval($request->custom_id);
        $customBalance = 0;
        if($get_balance>0 && $custom_id>0)
        {

            $customBalance = Balance::where('custom_id', $custom_id)->first();
            $customBalance = $customBalance?$customBalance->balance:0;


            $query->where('custom_id', $custom_id);

        }

            
        $start_time = strtotime($request->start_time)>0?strtotime($request->start_time):intval($request->start_time);
        $end_time = strtotime($request->end_time)>0?strtotime($request->end_time):intval($request->end_time);
        if ($start_time > 0 && $end_time > 0) {
            $query->where('create_at', '>=', $start_time)->where('create_at', '<=', $end_time);
        }
        $limit = $request->limit ?? 10;
        $list = $query->paginate($limit)->toArray();
        $list=paginateDataToArray($list);
        if($get_balance>0 && $custom_id>0){
            $list['customBalance']=$customBalance;
        }
        
        return $list;
    }

    public function getTotalWeightAttribute($value)
    {
        return $value / 10;
    }


    public function orderinfo(){
        return $this->hasOne(PurchaseOrder::class, 'id', 'order_id');
    }
}